package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void save(Employee employee,Long[] ids) {
        employeeMapper.insert(employee);

        if (ids!=null&&ids.length>0){
            for (Long id : ids) {
                employeeMapper.insertRelation(id,employee.getId());
            }
        }

    }

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
        employeeMapper.deleteRelation(id);
    }

    @Override
    public void update(Employee employee,Long[] ids) {
        employeeMapper.deleteRelation(employee.getId());
        employeeMapper.updateByPrimaryKey(employee);


        if (ids!=null && ids.length>0){
            for (Long id : ids) {
                employeeMapper.insertRelation(id,employee.getId());
            }
        }



    }

    @Override
    public Employee get(Long id) {

        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {

        return  employeeMapper.selectAll();
    }

    @Override
    public PageResult<Employee> query(QueryObject qo) {
        int count = employeeMapper.selectForCount(qo);
        if (count==0){
            return new PageResult<>
                    (qo.getCurrentPage(),qo.getPageSize(), Collections.emptyList(),count);
        }

        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageResult<>(qo.getCurrentPage(),qo.getPageSize(),employees,count);

    }



    @Override
    public Employee login(String username, String password) {

        Employee employee = employeeMapper.queryByName(username);

        if(employee==null){
            throw new RuntimeException("账号不存在");
        }


        if (!employee.getPassword().equals(password)){
            throw new RuntimeException("密码错误");
        }


        return employee;
    }

    @Override
    public void updatePwd(Employee employee, String newPassword) {

        employee.setPassword(newPassword);

        employeeMapper.updateByPrimaryKey(employee);


    }
}
